package com.example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Controller
@Slf4j
public class IndexController {

    @Autowired
    private MyConfig myConfig;

    @RequestMapping({"/index", "index.html"})
    public String index() {
        return "index";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String fileType = file.getContentType();
            String fileName = file.getOriginalFilename();
            String fileSize = file.getSize() / 1024 + "KB";
            log.info("文件类型：{},原文件名称：{},文件大小：{}", fileType, fileName, fileSize);
            String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            String path = myConfig.getSaveDirectory() + LocalDate.now().toString();
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.exists()) {
                dest.mkdirs();
            }
            file.transferTo(new File(path + "/" + newFileName));
            return Result.success(newFileName);
        } else {
            return Result.error("文件为空");
        }
    }
}
